<?php

namespace  App\Http\Controllers\V1;


use App\Helpers\Http\HttpClient;
use App\Helpers\Http\HttpCurl;
use App\Helpers\Http\HttpGet;
use App\Helpers\RestUtils;
use App\Http\Controllers\Controller;
use App\Models\Factory\PopupFactory;
use App\Models\Factory\UserFactory;
use App\Models\Orm\Popup;
use Illuminate\Http\Request;
use App\Helpers\RestResponseFactory;
use JsonSchema\Uri\Retrievers\Curl;


/**
 * 弹窗
 * Class PopupController
 * @package App\Http\Controllers\V1
 */
class PopupController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPopup(Request $request)
    {
        $data = $request->all();
        $popup = PopupFactory::getPopup($data['type'], $data['position']);
        $url = $popup ? $popup->img.'?imageInfo' : '';
        //获取七牛返回图片信息
        $qiNiu = json_decode(HttpGet::curl($url),true);

        if(empty($popup))
        {
            $popup['push_times'] = '';
            $popup['name'] = '';
            $popup['description'] = '';
            $popup['do_count'] = 0;
            $popup['position'] = int($data['position']);
            $popup['img'] = '';
            $popup['id'] = 1;
            $popup['update_time'] = '';
            $popup['create_time'] = '';
            $popup['status'] = '1';
            $popup['type'] = int($data['type']);
            $popup['url'] ='';
        }

        if($qiNiu)
        {

            $popup['aspectRatio'] =  number_format($qiNiu['width']/$qiNiu['height'],1);
        }else{

            $popup['aspectRatio'] = "1";
        }


        return $popup ? RestResponseFactory::ok($popup) : RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1208), 1208);

    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserPopup(Request $request)
    {
        $data = $request->all();
        //拿到中间件里赋值的userId
        $user = $request -> get('user');

        //首先判断有没有传我知道了这个状态

        if(isset($data['userStatus'])){
            $result = PopupFactory::createPopup($data['type'],$data['position'],$user ->id);
            return  $result ? RestResponseFactory::ok(RestUtils::getStdObj(), 200) : RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1209), 1209);
        }else
        {
            $userPopup = PopupFactory::getUserPopup($data['type'],$data['position'],$user ->id);
            return RestResponseFactory::ok($userPopup);
        }



    }
}
